package com.wushi.lenovo.asia5b.app_ui.other.dialog.shop;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.mvp.base.BaseDialogFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.images.WImageLoader;
import com.mvp.utils.DisplayUtils;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_model.good.bean.SkuBean;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.GoodsModel;
import com.wushi.lenovo.asia5b.app_model.h5.H5ShopBean;
import com.wushi.lenovo.asia5b.app_model.wish.GoodsDetailModel;
import com.wushi.lenovo.asia5b.app_ui.other.adapter.UpdateAdapter;
import com.wushi.lenovo.asia5b.app_ui.other.bean.ShopUpdateListener;
import com.wushi.lenovo.asia5b.app_widget.PlusView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/5/30.
 */
public class ShopUpdateDialogFragment extends BaseDialogFragment {
    @BindView(R.id.rv_shopcar)
    RecyclerView mRecyclerView;
    @BindView(R.id.plusview_shopcar)
    PlusView plusview_shopcar;
    @BindView(R.id.et_shopcar_remark)
    EditText et_shopcar_remark;
    @BindView(R.id.iv_shopcar_goodimg)
    ImageView iv_shopcar_goodimg;
    @BindView(R.id.ll_shopcar_price_vessel)
    LinearLayout ll_shopcar_price_vessel;//原价
    @BindView(R.id.tv_shopcar_price)
    TextView tv_shopcar_price;//原价
    @BindView(R.id.tv_shopcar_price2)
    TextView tv_shopcar_price2;//现价
    @BindView(R.id.iv_shopcar_close)
    ImageView iv_shopcar_close;
    @BindView(R.id.pb_shopcar)
    ProgressBar pb_shopcar;
    @BindView(R.id.tv_shopcar_percent)
    TextView tv_shopcar_percent;//折扣
    @BindView(R.id.bt_shopcar_submit)
    Button bt_shopcar_submit;
    @BindView(R.id.tv_shopcar_price3)
    TextView tv_shopcar_price3;//人民币价
    private final List<SkuBean> mDatas = new ArrayList<>();
    private Map<String, String> goods_attr_priceMap = null;//右边的价格
    private Map<String, String> goods_attr_price_rmMap = null;//下面的价格
    private Map<String, String> goods_attr_market_priceMap = null;//上面的价格
    private Map<String, String> goods_attr_discount;//百分比
    //    图里的 RM 86.80 是跟着 goods_attr_market_price
//    图里的 RM 48.98 是跟着 goods_attr_price_rm
//    图里的 RMB79.00 是跟着  goods_attr_market_price_seller
    GoodsModel goodsModel = null;
    private List<GoodsDetailModel.Multiple_priceBean> multiple_price;
    private UpdateAdapter mAdapter;
    private final Map<String, Integer> selectMap = new HashMap<>();//key:no  value:position
    private LinkedHashMap<String, List<SkuBean>> noKeyMap = new LinkedHashMap<>();//key值为no的属性集合
    private ShopUpdateViewModel mViewModel;
    private GoodsDetailModel goodsDetailModel;//请求回来的商品详情

    public static ShopUpdateDialogFragment newInstance(GoodsModel goodsModel) {
        ShopUpdateDialogFragment dialog = new ShopUpdateDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("goodsmodel", goodsModel);
        dialog.setArguments(bundle);
        return dialog;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mViewModel = ViewModelProviders.of(this).get(ShopUpdateViewModel.class);
        mViewModel.setLoadMvpView(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_shopupdate3;
    }


    @Override
    protected int getHeightStyle() {
        return (int) (DisplayUtils.getScreenWidthAndHight(getContext())[1] * 0.8f);
    }

    @Override
    protected void initView() {
        goodsModel = (GoodsModel) getArguments().getSerializable("goodsmodel");
        setImg(goodsModel.getImage());
//        setPriceText(model.getPrice());
        et_shopcar_remark.setText(goodsModel.getRemark());
        plusview_shopcar.setQty(goodsModel.getQuantity());
        if (goodsModel != null && goodsModel.getSell_case_value() > 1) {
            plusview_shopcar.setDoubleNum(goodsModel.getSell_case_value());
        }

        //中间加横线
        tv_shopcar_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        mAdapter = new UpdateAdapter(mDatas, selectMap);
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(getContext());
        mRecyclerView.setLayoutManager(flexboxLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
    }


    private void setImg(String img) {
        WImageLoader.displayImage(getContext(), img, iv_shopcar_goodimg);
    }

    @Override
    protected void initData() {
        mViewModel.getGoodDetail(goodsModel.getProduct_id(), goodsDetailModelResultModel -> {
            setResultModel(goodsDetailModelResultModel);
        });
    }

    @Override
    protected void initEvent() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int newPosition) {
                SkuBean newSkuBean = mAdapter.getItem(newPosition);
                if (newSkuBean.getItemType() == SkuBean.skutext) {
                    Integer oldPosition = selectMap.get(newSkuBean.no);
                    if (oldPosition == null) {
                        oldPosition = 0;
                    }
                    if (oldPosition != newPosition) {
                        selectMap.put(newSkuBean.no, newPosition);
                        mAdapter.notifyItemChanged(oldPosition);
                        mAdapter.notifyItemChanged(newPosition);
                        setPriceText();
                        if (newSkuBean.hasImgIcon) {
                            setImg(newSkuBean.imgIcon);
                        }
                    }
                }
            }
        });
    }

    @OnClick({R.id.iv_shopcar_close, R.id.bt_shopcar_submit})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_shopcar_close: {
                dismiss();
            }
            break;
            case R.id.bt_shopcar_submit: {
                int tag = (int) bt_shopcar_submit.getTag();
                if (tag == 0) {
                    ToastUtil.showToast(getString(R.string.aaa3));
                    return;
                }
                List<String> numbers = new ArrayList<>();//所有选中的skuno
                Iterator<Map.Entry<String, Integer>> positionIterator = selectMap.entrySet().iterator();
                while (positionIterator.hasNext()) {
                    Map.Entry<String, Integer> next = positionIterator.next();
                    Integer position = next.getValue();
                    if (mDatas.size() > position) {
                        SkuBean skuBean = mDatas.get(position);
                        numbers.add(skuBean.skuNo);
                    }
                }
                String attr = TextUtils.join(",", numbers);
                if (goodsModel != null) {
                    H5ShopBean h5ShopBean = new H5ShopBean();
                    h5ShopBean.setDoX("buy_1");
                    h5ShopBean.setNum(plusview_shopcar.getQty());
                    h5ShopBean.setProdId(goodsModel.getProduct_id());
                    h5ShopBean.setRemark(et_shopcar_remark.getText().toString());
                    h5ShopBean.setAttr(attr);
                    d("--->>>>>>>>---h5ShopBean:" + h5ShopBean.toString());
                    Fragment parentFragment = getParentFragment();
                    if (parentFragment != null && parentFragment instanceof ShopUpdateListener) {
                        ((ShopUpdateListener) parentFragment).callBack(h5ShopBean, goodsModel);
                    }

                }
                dismiss();
                break;
            }
        }
    }

    private void setPriceText() {
        if (multiple_price != null && multiple_price.size() != 0) {//按照数量算价格
            GoodsDetailModel.Multiple_priceBean findBean = null;
            int qty = plusview_shopcar.getQty();
            for (GoodsDetailModel.Multiple_priceBean multiple_priceBean : multiple_price) {
                int min_quantity = multiple_priceBean.getMin_quantityI();
                int max_quantity = multiple_priceBean.getMax_quantityI();

                if (qty >= min_quantity && qty <= max_quantity) {
                    findBean = multiple_priceBean;
                    break;
                }
            }
            if (findBean != null) {
                tv_shopcar_price.setText(String.format("%s %s", getString(R.string.rm), findBean.getBuyer_market_price() + ""));
                tv_shopcar_price2.setText(String.format("%s %s", getString(R.string.rm), findBean.getBuyer_price()));
                tv_shopcar_price3.setText(String.format("￥%s", findBean.getPrice()));
                tv_shopcar_percent.setText(findBean.getDiscount());
                if (TextUtils.equals("0%", findBean.getDiscount())) {
                    ll_shopcar_price_vessel.setVisibility(View.GONE);
                }
            }
            bt_shopcar_submit.setTag(1);
            bt_shopcar_submit.setEnabled(true);
        } else {//按照属性算价格
            String topPrice = getPriceBySelectOptions(goods_attr_market_priceMap, selectMap);
            String bottomPrice = getPriceBySelectOptions(goods_attr_price_rmMap, selectMap);
            String rightPrice = getPriceBySelectOptions(goods_attr_priceMap, selectMap);
            String percent = getPriceBySelectOptions(goods_attr_discount, selectMap);//如果有percent直接拿
            tv_shopcar_price.setText(String.format("RM %s", topPrice));
            tv_shopcar_price2.setText(String.format("RM %s", bottomPrice));
            tv_shopcar_price3.setText(String.format("￥%s", rightPrice));
            if (TextUtils.isEmpty(percent)) {//如果没有percent自己算
                //这个算法是错的,,应该是  (topPrice-bottomPrice)/topPrice
//                String divide = DecimalUtil.divide(topPrice, bottomPrice);
//                int percentI = (int) (StringUtils.parseFloat(divide) * 100);
//                percent = String.format("(-%d%%)", percentI);
                if (goodsDetailModel != null) {
                    percent = goodsDetailModel.getDiscount();
                }
            }
            tv_shopcar_percent.setText(percent);
            //价格百分百
            if (TextUtils.isEmpty(percent) || TextUtils.equals("0%", percent)) {
                ll_shopcar_price_vessel.setVisibility(View.GONE);
            } else {
                ll_shopcar_price_vessel.setVisibility(View.VISIBLE);
            }

//            bt_shopcar_submit.setEnabled(!TextUtils.isEmpty(bottomPrice));
            if (TextUtils.isEmpty(bottomPrice)) {
                ToastUtil.showToast(getString(R.string.aaa3));
                bt_shopcar_submit.setTag(0);
            } else {
                bt_shopcar_submit.setTag(1);
            }
            bt_shopcar_submit.setTag(TextUtils.isEmpty(bottomPrice) ? 0 : 1);
            bt_shopcar_submit.setEnabled(true);
            setEnableForDatas();
        }
    }

    //设置所有的item是否可以被点击
    private void setEnableForDatas() {
        for (Map.Entry<String, Integer> entry : selectMap.entrySet()) {
            Map<String, Integer> targetMap = new HashMap<>();
            for (Map.Entry<String, Integer> integerEntry : selectMap.entrySet()) {
                targetMap.put(integerEntry.getKey(), integerEntry.getValue());//先将目标map和当前选中map一致
            }
            d("--->>>>>>>>---" + String.format("选中组合:%s", targetMap.values().toString()));
            String noKey = entry.getKey();
            List<SkuBean> skuBeans = noKeyMap.get(noKey);
            for (SkuBean skuBean : skuBeans) {
                targetMap.put(noKey, skuBean.position);
                String priceBySelectOptions = getPriceBySelectOptions(goods_attr_price_rmMap, targetMap);
                skuBean.isEnable = !TextUtils.isEmpty(priceBySelectOptions);
                d("--->>>>>>>>---" + String.format("当前组合:%s,价格:%s", targetMap.values().toString(), priceBySelectOptions));
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * @param priceMap
     * @param tagetMap 被选中的属性集合
     * @return
     */
    private String getPriceBySelectOptions(Map<String, String> priceMap, Map<String, Integer> tagetMap) {
        String price = "";
        if (priceMap == null) {
            return price;
        }

        List<String> numbers = new ArrayList<>();//把所有的no，skuno集中起来
        Iterator<Map.Entry<String, Integer>> positionIterator = tagetMap.entrySet().iterator();
        while (positionIterator.hasNext()) {
            Map.Entry<String, Integer> next = positionIterator.next();
            Integer position = next.getValue();
            if (mDatas.size() > position) {
                SkuBean skuBean = mDatas.get(position);
//                numbers.add(skuBean.no);//不需要寻找no,skuno就够了
                numbers.add(skuBean.skuNo);
            }
        }
        Iterator<Map.Entry<String, String>> iterator = priceMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue();

            boolean findPrice = true;
            for (String number : numbers) {//必须保证所有的no，skuno都在这个key中
                if (!key.contains(number)) {
                    findPrice = false;
                    break;
                }
            }
            if (findPrice) {
                price = value;
                break;
            }

        }
        d("--->>>>>>>>---price:" + price);
        return price;
    }

    private boolean isMultiple(GoodsDetailModel goodsDetailModel) {
        multiple_price = goodsDetailModel.getMultiple_price();
        if (multiple_price == null || multiple_price.size() == 0) {
            return false;
        }
        //寻找最低值
        int minQty = 100000;
        for (GoodsDetailModel.Multiple_priceBean multiple_priceBean : multiple_price) {
            int min_quantityI = multiple_priceBean.getMin_quantityI();
            minQty = Math.min(minQty, min_quantityI);
        }
        d("--->>>>>>>>---minQty:" + minQty);
        plusview_shopcar.setMinQty(minQty);


        plusview_shopcar.setListener(new PlusView.QtyChangeListener() {//数量发生变化时,修改价格,因为价格与数量相关
            @Override
            public void call(int qty) {
                setPriceText();
            }
        });

        return true;
    }

    public void setResultModel(ResultModel<GoodsDetailModel> resultModel) {
        mDatas.clear();
        noKeyMap.clear();


        goodsDetailModel = resultModel.getData();
        //数据不能为空
        if (resultModel == null || goodsDetailModel == null) {
            return;
        }
        goods_attr_price_rmMap = goodsDetailModel.getGoods_attr_price_rm();
        goods_attr_market_priceMap = goodsDetailModel.getGoods_attr_market_price();
        goods_attr_priceMap = goodsDetailModel.getGoods_attr_price();
        goods_attr_discount = goodsDetailModel.getGoods_attr_discount();
        //特殊情况,这个没有商品属性,价格与数量有关
        if (isMultiple(goodsDetailModel)) {
        }

        LinkedHashMap<String, GoodsDetailModel.GoodsAttrCatBean> goods_attr_cat = goodsDetailModel.getGoods_attr_cat();
        if (goods_attr_cat == null || goods_attr_cat.size() == 0) {
            return;
        }

        //先集中所有属性值
        for (Map.Entry<String, GoodsDetailModel.GoodsAttrCatBean> entry : goods_attr_cat.entrySet()) {
            String noKey = entry.getKey();
            GoodsDetailModel.GoodsAttrCatBean noValue = entry.getValue();

            LinkedHashMap<String, String> imgIconMap = noValue.getImgIcon();
            LinkedHashMap<String, String> skuItemMap = noValue.getSkuItem();

            List<SkuBean> skuBeans = new ArrayList<>();
            for (Map.Entry<String, String> stringEntry : skuItemMap.entrySet()) {
                String skuItemKey = stringEntry.getKey();
                String skuItemValue = stringEntry.getValue();

                SkuBean skuBean = new SkuBean();
                skuBean.setItemType(SkuBean.skutext);
                skuBean.no = noKey;
                skuBean.skuNo = skuItemKey;
                skuBean.skuText = skuItemValue;
                skuBean.catName = noValue.getCatName();
                if (imgIconMap != null) {
                    skuBean.imgIcon = imgIconMap.get(skuBean.skuNo);
                    skuBean.hasImgIcon = true;
                }
                skuBeans.add(skuBean);
                noKeyMap.put(noKey, skuBeans);
            }

        }

        //将所有属性值以及对应的catname添加到adapter中
        for (Map.Entry<String, List<SkuBean>> entry : noKeyMap.entrySet()) {
            List<SkuBean> value = entry.getValue();
            if (value != null && value.size() != 0) {
                SkuBean skuBeanCatName = new SkuBean();
                skuBeanCatName.setItemType(SkuBean.catname);
                skuBeanCatName.catName = value.get(0).catName;
                mDatas.add(skuBeanCatName);
                mDatas.addAll(value);
            }
        }
        //赋值position，以备后用
        int position = 0;
        for (SkuBean skuBean : mDatas) {
            skuBean.position = position;
            position++;
        }

        //寻找该商品的属性坐标
        String option = goodsModel.getOption();//这个是购物车过来的商品的属性
        if (!TextUtils.isEmpty(option)) {
            String[] options = option.split(",");
            if (options != null) {
                for (String s : options) {
                    for (SkuBean skuBean : mDatas) {
                        if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(skuBean.skuNo) && s.contains(skuBean.skuNo)) {
                            selectMap.put(skuBean.no, skuBean.position);
                        }
                    }
                }
            }
        }

        mAdapter.notifyDataSetChanged();
        setPriceText();

    }

    @Override
    public void showLoadingBar(Object dississTag) {
        pb_shopcar.setVisibility(View.VISIBLE);
    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        pb_shopcar.setVisibility(View.GONE);
    }
}
